<?php

namespace App\Http\Controllers\Order;

use AlibabaCloud\SDK\Dingtalk\Vcalendar_1_0\Models\ListCalendarsResponseBody\response;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Order\Outboundorder;
use App\Http\Validate\Order\Outboundordersub;
use App\Models\Custom\Custom;
use App\Models\Order\Outboundorderwithpay;
use App\Models\Order\Saleimplementation;
use App\Models\Order\Saleimplementationsub;
use App\Models\Order\Saleorder;
use App\Models\Order\Saleorderfee as ModelSaleorderfee;
use App\Models\Order\Saleorder as ModelSaleorder;
use App\Models\Order\Saleorderinvoice;
use App\Models\Order\Salesorder;
use App\Models\Order\Salesorder as ModelSalesorder;
use App\Models\Order\Salesordersub;
use App\Models\Order\Salesordersub as ModelSalesordersub;
use App\Models\Order\Outboundorder as ModelOutboundorder;
use App\Models\Order\Outboundordersub as ModelOutboundordersub;
use App\Models\Order\Outboundordersubsub as ModelOutboundordersubsub;
use App\Models\Stock\Stock as ModelStock;
use App\Models\Stock\StockSub;
use App\Models\Stock\StockSub as ModelStockSub;
use App\Models\Systemparam\Systemparam as ModelSystemparam;
use App\Models\Warehouse\WarehouseList;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\CommonExcelExport;
use App\Services\Common\SnCode;
use App\Services\Common\TableExtFeild;
use App\Services\Stock\Stock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 出库单模块
 */
class OutboundorderController extends BaseController
{
    /**
     * 获取表头
     */
    public function gettablefield()
    {
        $cpid = $this->mangerinfo['cpid'];
        $mainextfield = TableExtFeild::getFeildTitle((new ModelOutboundorder())->getTable(), $cpid);
        $subextfield = TableExtFeild::getFeildTitle((new ModelOutboundordersub())->getTable(), $cpid);
        return response()->json([
            'code' => '000',
            'msg' => '获取成功',
            'data' => [
                'mainextfield' => $mainextfield,
                'subextfield' => $subextfield
            ]
        ]);
    }

    /**
     * 编辑表头字段
     */
    public function changeorderfield(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $sub_order_id = $request->sub_order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = ModelOutboundorder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $suborderinfo = ModelOutboundordersub::where(['p_id' => $order_id, 'id' => $sub_order_id])->first();
        $data = TableExtFeild::getTableFeildData($request);
        if ($suborderinfo) {
            ModelOutboundordersub::where(['p_id' => $order_id, 'id' => $sub_order_id])->update($data);
        } else {
            ModelOutboundorder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->update($data);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 添加
     *
     * 发货单有多个的时候子订单已经生成了出库单就不允许再次生成，
     * 还没有生成出库单的子订单是可以生成出库单的；子订单的是不允许拆分的
     * 程阳 2025.06.16
     *
     *
     */
    public function dopostadd(Request $request)
    {
        //判断销货单是否存在
        $sales_id = $request['id'];
        $isexist = ModelSalesorder::where('id', $sales_id)->first();
        if (!$isexist) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        //校验出库单
        $params = [
            'order_number',
            'document_date',
            'bill_type',
            'business_type',
            'custom_id',
            'custom_name',
            'settlement_company',
            'wagon_number',
            'driver_phone_number',
            'suborder',
            'warehouse_return_order',
            'remark'
        ];
        $req_data = $request->only($params);
        // 票据类型目前只有专票
        $req_data['bill_type'] =1;
        $req_data['business_type'] =1;
        $validate = new Outboundorder('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $suborder = is_array($req_data['suborder']) ? $req_data['suborder'] : json_decode($req_data['suborder'], true);
        $subvalidate = new Outboundordersub('add');
        foreach ($suborder as $item) {
            if (!$subvalidate->check($item)) {
                return response()->json(['code' => '001', 'msg' => $subvalidate->getError()]);
            }

            $sales_sub_one = ModelSalesordersub::where('id', $item['id'])->first();
            if (!$sales_sub_one) {
                return response()->json(['code' => '001', 'msg' => '子订单不存在']);
            }
            $sales_sub_one = $sales_sub_one->toArray();
            if ($sales_sub_one['produce_status'] == config('constants.produce_status.produced')) {
                return response()->json(['code' => '001', 'msg' => '已生成子订单不能生成']);
            }
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $manger_name = $mangerinfo['realname'] ?? 0;

        //获取公司成本
        $one = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'company_costs'])->first();
        if ($one) {
            $companycosts = $one->value;
        } else {
            $companycosts = 10;
        }

        //其他费用
        $otherfeetotal = 0;
        $otherfeedata = ModelSaleorderfee::where('order_number', $req_data['order_number'])->get();
        if ($otherfeedata) {
            foreach ($otherfeedata as $v) {
                $otherfeetotal = $otherfeetotal + $v->fee;
            }
        }

        $SaleDeliveryDetails = []; //销货单明细
        DB::beginTransaction();
        try {
            $saleInfo = ModelSaleorder::where('order_number', $req_data['order_number'])->first()->toArray();
//            foreach ($suborder as $new) {


//                if(isset($new["suborder"])){
//                    foreach ($new["suborder"] as $item){
//                        ModelStockSub::where(['id' => $item['id']])->update([
//                            //'can_use_pieces' => DB::raw('can_use_pieces - ' . $new['pieces']),
//                            //'can_use_weight' => DB::raw('can_use_weight - ' . mathfuncweight('mul', $new['weight'], 10000)),
//                            'locked_pieces' => DB::raw('locked_pieces - ' . $item['pieces']),
//                            'locked_weight' => DB::raw('locked_weight - ' . mathfuncweight('mul', $item['weight'], 10000)),
//                            'current_pieces' => DB::raw('current_pieces - ' . $item['pieces']),
//                            'current_weight' => DB::raw('current_weight - ' . mathfuncweight('mul', $item['weight'], 10000)),
//                        ]);
//                    }
//                }
//            }
            $SaleorderController = new SaleorderController($request);
            $outbound_weight = $outbound_amount = $outbound_pieces = 0;
            foreach ($suborder as $item) {
                ModelSalesordersub::where('id', $item['id'])->update([
                    'produce_status' => config('constants.produce_status.produced'),
                    'update_at' => time(),
                ]);

              //  $unit_price = mathfuncmoney('mul', $item['unit_price'], 100);
               // $guiding_price = mathfuncmoney('mul', $item['guiding_price'] ?? 0, 100);

//                if ($item['is_sys_purchase'] == 2) {
//                } else {
//                    // 此处计算业绩和计提有问题
//                    $accrual = $unit_price - $guiding_price + $companycosts;
//                    $performance = $accrual * mathfuncweight('mul', $item['weight'] ?? 0, 10000) - $otherfeetotal;
//                }


                $pieces = $item['pieces'] ?? 0;
                // 孙
                $subsuborder = isset($item['suborder']) ? (is_array($item['suborder']) ? $item['suborder'] : (is_array(json_decode($item['suborder'], true)) ? json_decode($item['suborder'], true) : [])) : [];

                if (!empty($subsuborder)) {
                    $son_son_pieces = 0;
                    foreach ($subsuborder as $subitem) {
                        $son_son_pieces += $subitem['pieces'];
                        /***
                         *  校验孙订单 库存是否充足，件数、重量
                         *  can_use_pieces  total_weight
                         */
                        $StockSub = ModelStockSub::where('id',$subitem['id'])->first();
                        if($StockSub['can_use_pieces'] < $subitem['pieces']){
                            return response()->json(['code' => '001', 'msg' => '库存件数不足']);
                        }
                    }
                    if ($pieces != $son_son_pieces) {
                        return response()->json(['code' => '001', 'msg' => '子订单件数与孙订单件数不一致']);
                    }
                }elseif ($item['archive_type']==2){
                    // 如果过磅的库存存在孙
                    $stock_id = $item['stock_id']??0;
                    $stocksub =ModelStockSub::query()
                        ->where(['archive_type'=>2,'stock_id'=>$stock_id,'archive_no'=>$item['archive_no']])
                        ->first('id');

                    if((!empty($stocksub)&&empty($subsuborder))|| (empty($stocksub)&&!empty($subsuborder))){
                        return response()->json(['code' => '001', 'msg' => '孙订单为空，不能出库']);

                    }
                } else {
                    return response()->json(['code' => '001', 'msg' => '孙订单为空，不能出库']);
                }

                //$saleInfo['purchase_stockin_order_sn_code']  查到的这个值可能有问题,多个销货单情况下
                $data_sub_item[] = [
                    'sales_id' => $item['id'],
                    'cpid' => $cpid,
                    'manger_id' => $manger_id,
                    'purchase_stockin_order_sn_code' => $saleInfo['purchase_stockin_order_sn_code'] ?? '',
                    'material_id' => $item['material_id'],
                    'stock_id' => $item['stock_id'],
                    'archive_no' => $item['archive_no'],
                    'warehouse_name' => $item['warehouse_name'],
                    'steel_factory_name' => $item['steel_factory_name'],
                    'archive_type' => $item['archive_type'],
                    'archive_name' => $item['archive_name'],
                    'archive_spec' => $item['archive_spec'],
                    'archive_material' => $item['archive_material'],
                    'breed_name' => $item['breed_name'],
                    'weight' => mathfuncweight('mul', $item['weight'], 10000),
                    'pieces' => $pieces,
                    'length' => $item['length'] ?? 0,
                    'unit_price' => mathfuncmoney('mul', $item['unit_price'], 100),
                    'total' => mathfuncmoney('mul', $item['total'], 100),
                    'accrual' => $item['is_sys_purchase']==1? mathfuncmoney('mul',$item['accrual'], 100) : 0,
                    'performance' =>$item['is_sys_purchase']==1?mathfuncmoney('mul',$item['performance'], 100) : 0,
                    'suborder' => json_encode($item['suborder'], true),
                    'remark' => $item['remark'],
                    'create_at' => time(),
                ];


                $outbound_weight = $outbound_weight + mathfuncweight('mul', $item['weight'], 10000);
                $outbound_amount = $outbound_amount + mathfuncmoney('mul', $item['total'], 100);
                $outbound_pieces = $outbound_pieces + $pieces;

                /**
                 *  T+测试发现 数量(重量)为0 无法新增
                 *
                 */
                if(($item['weight'] * 100) > 0){
//                    $business_performance = 0;
//                    if(isset($item["diff"])){
//                        if($item["diff"] * 100 > 0){
//                            //performance-diff 业绩由于前端计算不准,需要后端计算
//                            $business_performance = mathfuncmoney('sub',$item["performance"],$item["diff"],2);//业绩
//
//                        }
//                    }
                    $SaleDeliveryDetails[] = [
                        "Warehouse" => ["Code" => WarehouseList::where(['warehouse_name' => $item['warehouse_name'], 'cpid' => $cpid])->value('warehouse_no')],
                        "Inventory" => ["Code" => $item['archive_no']],
                        "Unit" => ["Name" => "吨"],
                        "Unit2" => ["Name" => "件"],
                        "Quantity" => $item['weight'],
                        "Quantity2" => $pieces,//件数
                        "TaxRate" => "0",
                        "OrigTaxPrice" => $item['unit_price'],
                        "OrigTaxAmount" => $item['total'],
                        "OrigDiscount" => $item['total'],
                        "DetailMemo" => $item['remark'],
                        "DynamicPropertyKeys"=>["pubuserdefnvc1","pubuserdefnvc2","pubuserdefnvc3","priuserdefnvc1","pubuserdefdecm1","pubuserdefdecm4"],//件数(数量2)priuserdefnvc1(私有字符串1) stock_id(库存id)priuserdefnvc2(私有字符串1)
                        "DynamicPropertyValues" => [$item['steel_factory_name'],$item['breed_name'],$item['archive_material'],strval($pieces),strval($item["accrual"]),strval($item["performance"])],
                        //performance 业绩(pubuserdefdecm4)  accrual 计提(pubuserdefdecm1)  accrual 计提 performance-diff 业绩
                        //SaleDelivery.SaleDeliveryDetails.topFHCCode  返货单号
                    ];
                }

                /*****
                 * 出库时，自采场景校准扣除的库存，
                 * 原因：自采销售订单，扣除不准确库存，采购入库量如果不足，钢材库存变为负值。钢材单重 变为负值，无法正常在创建订单
                 * 目的:防止自采订单钢材，库存变为负值
                 * 逻辑搁置，订单时 加已锁，减可用。 出库 减去已锁 减去现存。
                 *
                 * 常规订单，没问题。自采的话，要重新增减库存?
                 *
                 **/
            }


            /**
             *  发货单出库时,已锁 现存释放. 可用不变 2025.3.12
             *
             *  父库存释放,子库存未释放 stock_sub_id
             *  释放子库存，2025.04.07
             *
             */

            $incrDecrStock =  $SaleorderController->outboundDecrStockInSale($suborder,'decr');
            if($incrDecrStock['code'] != '000'){
                return response()->json($incrDecrStock);
            }
            //修改出库单生成状态
            //$sales_sub = ModelSalesordersub::where('sale_id', $sales_id)->get();
            //$produce_status = 2;
            // foreach ($sales_sub as $v) {
            //     if ($v->produce_status == 1) {
            //         $produce_status = 1;
            //     }
            // }
            /****
             * 直接修改发货单状态，改为 检查销售发货单，子订单全部出库后，发货完成，
             * 2025.06.16
             *
            */
            $is_produced = $this->checkWarehouseOut($sales_id);
            if($is_produced['code'] == '001'){
                return response()->json($is_produced);
            }
            if($is_produced['is_produced']){
                ModelSalesorder::where('id', $sales_id)->update([
                    'produce_status' => config('constants.produce_status.produced'),
                    'update_at' => time(),
                ]);
            }else{
                ModelSalesorder::where('id', $sales_id)->update([
                    'produce_status' => config('constants.produce_status.produceing'),
                    'update_at' => time(),
                ]);
            }
//            ModelSalesorder::where('id', $sales_id)->update([
//                'produce_status' => $produce_status,
//                'update_at' => time(),
//            ]);
            //




            //添加出库单
            $document_number = SnCode::getSnCode('CK_');
            $data = [
                'cpid' => $cpid,
                'manger_id' => $manger_id,
                'manger_name' => $manger_name,
                'sales_id' => $sales_id,
                'order_number' => $req_data['order_number'],
                'document_number' => $document_number,
                'document_date' => $req_data['document_date'],
                'bill_type' => $req_data['bill_type'],
                'business_type' => $req_data['business_type'],
                'custom_id' => $req_data['custom_id'],
                'custom_name' => $req_data['custom_name'],
                'settlement_company' => $req_data['settlement_company'] ?? '',
                'wagon_number' => $req_data['wagon_number'] ?? '',
                'driver_phone_number' => $req_data['driver_phone_number'] ?? '',
                'warehouse_return_order' => $req_data['warehouse_return_order'],
                'remark' => $req_data['remark'],
                'sales_create_at' => $isexist->create_at,
                'create_at' => time(),
            ];
            $p_id = ModelOutboundorder::create($data)->id;


            //销售订单执行情况
            Saleimplementation::where('order_number', $req_data['order_number'])->update([
                'outbound_weight' => DB::raw('outbound_weight + ' . $outbound_weight),
                'outbound_amount' => DB::raw('outbound_amount + ' . $outbound_amount),
                'outbound_pieces' => DB::raw('outbound_pieces + ' . $outbound_pieces)
            ]);

            foreach ($data_sub_item as $item) {
                //添加出库子订单
                $outbound_id = ModelOutboundordersub::create($item + [
                    'p_id' => $p_id,
                    // 'stock_sub_id' => $item['id'],
                ])->id;

                if (!empty($item['suborder'])) {
                    $item['suborder'] = json_decode($item['suborder'], true);
                    foreach ($item['suborder'] as $suborder) {
                        unset($suborder['p_id']);
                        /***
                         * $suborder 前端传入的 初始数据, 金额：元
                         *
                        */
                        if(isset($suborder["total"])) $suborder["total"] = mathfuncweight('mul', $suborder["total"], 100);
                        if(isset($suborder["total_weight"])) $suborder["total_weight"] = mathfuncweight('mul', $suborder["total_weight"], 10);
                        if(isset($suborder["weight"])) $suborder["weight"] = mathfuncweight('mul', $suborder["weight"], 10);

                        $data_sub_sub_item = [
                            'cpid' => $cpid,
                            'p_id' => $outbound_id,
                            'manger_id' => $manger_id,
                            'create_at' => time(),
                            'stock_sub_id' => $suborder['id'] //子库存id
                        ] + $suborder;
                        unset($data_sub_sub_item['id']);
                        /***
                         *
                        */
                        ModelOutboundordersubsub::create($data_sub_sub_item);
                    }
                }

                //更新销售执行子订单
                Saleimplementationsub::where([
                    'cpid' => $cpid,
                    'sales_id' => $item['sales_id'],
                ])->update([
                    'outbound_id' => $outbound_id,
                    'outbound_weight' => DB::raw('outbound_weight + ' . $item['weight']),
                    'outbound_amount' => DB::raw('outbound_amount + ' . $item['total']),
                    'outbound_pieces' => DB::raw('outbound_pieces + ' . $item['pieces']),
                    'update_at' => time()
                ]);
            }

            //生成出库收款对账单
            $data = [
                'cpid' => $cpid,
                'manger_id' => $manger_id,
                'type' => 1,
                'document_number' => $document_number,
                'order_date' => $req_data['document_date'],
                'custom_id' => $req_data['custom_id'],
                'settlement_company' => $req_data['settlement_company'] ?? '',
                'total_weight' => $outbound_weight,
                'total_money' => $outbound_amount,
                'create_at' => time(),
            ];
            Outboundorderwithpay::create($data);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '出库单生成失败'.$e->getLine().$e->getMessage()]);
        }

        //--2025-08-14  修改为审核通过后再同步订单
//        /***
//         *  销货单
//         *
//         */
//        $Chanjet_param = [
//            "dto" => [
//                "ExternalCode" => $req_data['order_number'] . '|' . $document_number,
//                "Code" => $document_number . '|' . $sales_id, //出库单编号 + 销货单id
//                "IsModifiedCode" => "true",
//                "VoucherDate" => date('Y-m-d', $req_data['document_date']),
//                "BusinessType" => ["Code" => $req_data['business_type'] == "1" ? "15" : "16"], //15 普通销售 16退货
//                "InvoiceType" => ["Code" => $req_data['bill_type'] == "1" ? "01" : "00"], //00--普通发票，01--专用发票，02–收据
//                "Customer" => ["Code" => Custom::where('id', $req_data['custom_id'])->value('company_code')],
//                "SaleDeliveryDetails" => $SaleDeliveryDetails
//            ]
//        ];
//        if ($req_data['wagon_number']) {
//            $Chanjet_param["dto"]["DynamicPropertyKeys"] = ["pubuserdefnvc1"];
//            $Chanjet_param["dto"]["DynamicPropertyValues"] = [$req_data['wagon_number']];
//        }
//        //结算公司
//        if($req_data['settlement_company']){
//            //$Chanjet_param["dto"]["SettleCustomer"] = ["Code"=>$req_data['settlement_company']];
//            $Chanjet_param["dto"]["SettleCustomer"] = $Chanjet_param["dto"]["Customer"];
//        }
//        //部门信息
//        if($mangerinfo['sys_dpm_id']){
//            $Chanjet_param["dto"]["Department"] = ["Code"=>$mangerinfo['sys_dpm_id']];
//        }
//        //Clerk
//        if($mangerinfo['code_no']){
//            $Chanjet_param["dto"]["Clerk"] = ["Code"=>$mangerinfo['code_no']];
//        }
//        if ($req_data['remark']) {
//            $Chanjet_param["dto"]["Memo"] = $req_data['remark'];
//        }
//
//        $requestData = [
//            "api" => "saleDeliveryCreate",
//            "param" => $Chanjet_param,
//            "mangerinfo" => $this->mangerinfo
//        ];
//        \App\Jobs\Sale::dispatch($requestData);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelOutboundorder::getList($request, $memberinfo, $isgetall);
        if ($list['list']) foreach ($list['list'] as $key => $value) {
            foreach ($value['suborder'] as $k => $v) {
                $list['list'][$key]['suborder'][$k]['weight'] = mathfuncweight('div', $v['weight'], 10000, 4);
                //$list['list'][$key]['suborder'][$k]['unit_price'] = mathfuncmoney('div', $v['unit_price'], 100, 2);前端已经算了
                $list['list'][$key]['suborder'][$k]['total'] = mathfuncmoney('div', $v['total'], 100, 2);

                $list['list'][$key]['suborder'][$k]['accrual'] = mathfuncmoney('div', $v['accrual'], 100, 2);
                $list['list'][$key]['suborder'][$k]['performance'] = mathfuncmoney('div', $v['performance'], 100, 2);

                $suborder = ModelOutboundordersubsub::where(['p_id' => $v['id']])->get();
                if ($suborder) {
                    $suborder = $suborder->toArray();
                    foreach ($suborder as $k1 => $v1){
                        $suborder[$k1]['total'] = mathfuncmoney('div',$v1['total'],100,2);
                    }
                } else {
                    $suborder = [];
                }

                $list['list'][$key]['suborder'][$k]['suborder'] = $suborder;
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelOutboundorder::getone($id);
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $one = $one->toArray();
        if ($one['suborder']) foreach ($one['suborder'] as $key => $value) {
            $one['suborder'][$key]['weight'] = mathfuncweight('div', $value['weight'], 10000, 4);
            $one['suborder'][$key]['unit_price'] = mathfuncmoney('div', $value['unit_price'], 100, 2);
            $one['suborder'][$key]['total'] = mathfuncmoney('div', $value['total'], 100, 2);

            $one['suborder'][$key]['accrual'] = mathfuncmoney('div', $value['accrual'], 100, 2);
            $one['suborder'][$key]['performance'] = mathfuncmoney('div', $value['performance'], 100, 2);

            $one['suborder'][$key]['suborder'] = ModelOutboundordersubsub::where(['p_id' => $value['id']])->get()->toArray();
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    /**
     * 子订单详情
     */
    public function getsubone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelOutboundordersub::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '子订单不存在']);
        }
        $one = $one->toArray();

        $one['weight'] = $one['weight'] == 0 ? 0 : $one['weight'] / 10000;
        $one['unit_price'] = $one['unit_price'] / 100;
        $one['total'] = $one['total'] == 0 ? 0 : $one['total'] / 100;
        $one['guiding_price'] = $one['guiding_price'] / 100;
        $one['accrual'] = $one['accrual'] == 0 ? 0 : $one['accrual'] / 100;
        $one['performance'] = $one['performance'] == 0 ? 0 : $one['performance'] / 100;

        $order = ModelOutboundorder::where('id', $one['p_id'])->first()->toArray();
        $one['custom_info'] = Custom::where('id', $order['custom_id'])->first()->toArray();

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    /**
     * 编辑业绩
     */
    public function editperformance(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelOutboundordersub::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '子订单不存在']);
        }
        $performance = mathfuncmoney('mul', $request->performance, 100) ?? 0;
        ModelOutboundordersub::where('id', $id)->update(['performance' => $performance]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 编辑差额、重新计算业绩
     */
    public function editdifference(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelOutboundordersub::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '子订单不存在']);
        }
        $one = $one->toArray();

        $difference = mathfuncmoney('mul', $request->difference, 100) ?? 0;
        // 业绩+差额
        $performance = $one['performance'] + $difference;
        ModelOutboundordersub::where('id', $id)->update(['performance' => $performance, 'difference' => $difference]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 申请开票
     */
    public function invoice(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelOutboundorder::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        // 根据出库单的订单编号查询销售订单是否预开发票
        $order_number = $one->order_number;

        // 使用select直接获取invoice_status，避免获取整个模型
        $invoice_status = Saleorder::where('order_number', $order_number)
            ->value('invoice_status');

        // 判断如果没有申请预开发票不能继续开票
        if ($invoice_status !== 2) {
            return response()->json(['code' =>'001','msg'=>'请先申请预开发票']);
        }
        $suborder = is_array($request['suborder']) ? $request['suborder'] : json_decode($request['suborder'], true);

        foreach ($suborder as $item) {
            $examine_status = ModelOutboundordersub::where('id', $item['id'])->value('examine_status');
            if($examine_status != 1)
            {
                return response()->json(['code' => '001', 'msg' => '已经提交开票申请，请勿重复提交！']);
            }
        }

        DB::beginTransaction();
        try {
            ModelOutboundorder::where('id', $id)->update(
                ['invoice_status' => 2, 'update_at' => time()]
            );

            $contract_code = getRandomString();
            foreach ($suborder as $item) {
                ModelOutboundordersub::where('id', $item['id'])->update([
                    'invoice_status' => 2,
                    'examine_status' => 2,
                    'contract_url' => $request->contract_url,
                    'contract_code' => $contract_code,
                    'invoice_at'=>time(),
                    'update_at' => time()
                ]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '开票失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 编辑
     */
    public function doinvoiceedit(Request $request)
    {
        //校验参数
        $params = [
            'id',
            'contract_url',
        ];

        $req_data = $request->only($params);
        $id = $req_data['id'] ?? 0;

        $one = ModelOutboundordersub::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '子订单不存在']);
        }

        if ($one->invoice_status == 3) {
            return response()->json(['code' => '001', 'msg' => '订单已开票不能修改']);
        }

        ModelOutboundordersub::where('id', $id)->update([
            'contract_url' => $req_data['contract_url'],
        ]);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 开票列表
     */
    public function invoicelist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;

        $invoice_status = $request->query('invoice_status', 2);
        $request->merge(['invoice_status' => $invoice_status]);

        $list = ModelOutboundorder::getList($request, $memberinfo, $isgetall);
        if ($list['list']) foreach ($list['list'] as $key => $value) {
            foreach ($value['suborder'] as $k => $v) {
                $list['list'][$key]['suborder'][$k]['weight'] = $v['weight'] / 10000;
                $list['list'][$key]['suborder'][$k]['unit_price'] = $v['unit_price'] / 100;
                $list['list'][$key]['suborder'][$k]['total'] = $v['total'] / 100;
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 开票操作
     */
    public function handleinvoice(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelOutboundordersub::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '子订单不存在']);
        }

        if ($one->examine_status != 3) {
            return response()->json(['code' => '001', 'msg' => '合同没有审核通过']);
        }

        if ($one->invoice_status != 2) {
            return response()->json(['code' => '001', 'msg' => '已通过或者未发起开票']);
        }

        ModelOutboundordersub::where('id', $id)->update(
            ['invoice_status' => $request->invoice_status, 'invoice_at' => time()]
        );

        // 根据父订单ID查询是否有未完成开票的子订单
        $hasUninvoicedSuborder = ModelOutboundordersub::where('p_id', $one->p_id)
            ->where('invoice_status', '<', 3)
            ->exists();

        if (!$hasUninvoicedSuborder) {
            // 获取关联出库单的订单编号
            $order_number = ModelOutboundorder::where('id', $one->p_id)->value('order_number');

            // 更新预开票主订单状态为已开票（状态码3）
            Saleorderinvoice::where('order_number', $order_number)
                ->update(['status' => 3]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 合同审核
     */
    public function handleexamine(Request $request)
    {
        $id = $request->id ?? 0;
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;

        $one = ModelOutboundordersub::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '子订单不存在']);
        }

        if ($one->examine_status != 2) {
            return response()->json(['code' => '001', 'msg' => '合同已经审核或者未发起审核']);
        }

        //获取订单编号
        $outboundinfo = ModelOutboundorder::where('id', $one->p_id)->first();
        $order_number = $outboundinfo->order_number;
        //根据订单编号修改预开票的主订单状态
        Saleorderinvoice::where('order_number', $order_number)->update(['status' => 2]);

        ModelOutboundordersub::where('id', $id)->update(
            ['examine_status' => $request->examine_status, 'update_at' => time()]
        );

        //查询主订单下的所有子订单是否都已经审核通过
        //如果审核通过在给T+同步销货单
        $suborder = ModelOutboundordersub::where('p_id', $one->p_id)->get();
        $allApproved = $suborder->every(function ($item) {
            return $item->examine_status == 3;
        });
        $allstatus = 0;
        if ($allApproved) {
            $SaleDeliveryDetails = $this->buildSaleDeliveryDetails($suborder, $cpid);

            if (!empty($SaleDeliveryDetails)) {
                $Chanjet_param = $this->buildChanjetParam(
                    $outboundinfo,
                    $order_number,
                    $mangerinfo,
                    $SaleDeliveryDetails
                );

                $requestData = [
                    "api" => "saleDeliveryCreate",
                    "param" => $Chanjet_param,
                    "mangerinfo" => $this->mangerinfo
                ];

                \App\Jobs\Sale::dispatch($requestData);
            }
            $allstatus = 1;
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'allstatus' => $allstatus]);
    }

    /**
     * 开票操作
     */
    public function handleinvoicemore(Request $request)
    {
        $order_id_arr = $request->order_id_arr ?? [];
        $order_id_arr = is_array($order_id_arr) ? $order_id_arr : (is_array(json_decode($order_id_arr, true)) ? json_decode($order_id_arr, true) : []);
        if (count($order_id_arr) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $ids = [];
        $pids = [];
        $errormsg = false;

        DB::beginTransaction();
        try {

            foreach ($order_id_arr as $id)
            {
                $one = ModelOutboundordersub::where('id', $id)->first();
                if (!$one) {
//                    return response()->json(['code' => '001', 'msg' => '子订单不存在']);
                    $errormsg = true;
                    continue;
                }

                if ($one->examine_status != 3) {
//                    return response()->json(['code' => '001', 'msg' => '合同没有审核通过']);
                    $errormsg = true;
                    continue;
                }

                if ($one->invoice_status != 2) {
//                    return response()->json(['code' => '001', 'msg' => '已通过或者未发起开票']);
                    $errormsg = true;
                    continue;
                }
                $pids[] = $one->p_id;
                $ids[] = $id;
            }
            ModelOutboundordersub::whereIn('id', $ids)->update(
                ['invoice_status' => $request->invoice_status, 'invoice_at' => time()]
            );
            //$pids 去重
            $pids = array_unique($pids);
            foreach ($pids as $p_id)
            {
                // 根据父订单ID查询是否有未完成开票的子订单
                $hasUninvoicedSuborder = ModelOutboundordersub::where('p_id', $p_id)
                    ->where('invoice_status', '<', 3)
                    ->exists();

                if (!$hasUninvoicedSuborder) {
                    // 获取关联出库单的订单编号
                    $order_number = ModelOutboundorder::where('id', $p_id)->value('order_number');

                    // 更新预开票主订单状态为已开票（状态码3）
                    Saleorderinvoice::where('order_number', $order_number)
                        ->update(['status' => 3]);
                }
            }

            DB::commit();
            if($errormsg)
            {
                return response()->json(['code' => '000', 'msg' => '部分选项不可操作，系统将会自动跳过，执行处理其余符合审批/开票条件的选项']);
            }else{
                return response()->json(['code' => '000', 'msg' => '操作成功']);
            }

        }catch (\Exception $e){
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '开票失败' . $e->getMessage()]);
        }
    }

    /**
     * 合同审核
     */
    /**
     * 合同审核
     */
    public function handleexaminemore(Request $request)
    {
        $order_id_arr = $request->order_id_arr ?? [];
        $order_id_arr = is_array($order_id_arr) ? $order_id_arr : (is_array(json_decode($order_id_arr, true)) ? json_decode($order_id_arr, true) : []);
        if (count($order_id_arr) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        $processedIds = [];
        $errorMessages = [];
        $parentOrderIds = []; // 用于记录处理过的父订单ID

        DB::beginTransaction();
        try {
            foreach ($order_id_arr as $id) {
                $result = $this->processSingleExamine($id, $request->examine_status);
                if ($result['success']) {
                    $processedIds[] = $id;
                    // 获取父订单ID用于后续检查是否全部完成
                    $subOrder = ModelOutboundordersub::where('id', $id)->first();
                    if ($subOrder) {
                        $parentOrderIds[] = $subOrder->p_id;
                    }
                } else {
                    $errorMessages[] = "ID {$id}: {$result['message']}";
                }
            }

            // 去重父订单ID
            $parentOrderIds = array_unique($parentOrderIds);

            // 检查每个父订单是否所有子订单都已审核通过，如果是则同步到T+系统
            $mangerinfo = $this->mangerinfo;
            $cpid = $mangerinfo['cpid'] ?? 0;

            foreach ($parentOrderIds as $parentId) {
                // 检查该父订单下的所有子订单是否都已审核通过
                $allSubOrders = ModelOutboundordersub::where('p_id', $parentId)->get();
                $allApproved = $allSubOrders->every(function ($item) {
                    return $item->examine_status == 3;
                });

                // 如果全部审核通过，则同步到T+系统
                if ($allApproved) {
                    $SaleDeliveryDetails = $this->buildSaleDeliveryDetails($allSubOrders, $cpid);

                    if (!empty($SaleDeliveryDetails)) {
                        // 获取出库单信息
                        $outboundinfo = ModelOutboundorder::where('id', $parentId)->first();
                        if ($outboundinfo) {
                            $order_number = $outboundinfo->order_number;

                            $Chanjet_param = $this->buildChanjetParam(
                                $outboundinfo,
                                $order_number,
                                $mangerinfo,
                                $SaleDeliveryDetails
                            );

                            $requestData = [
                                "api" => "saleDeliveryCreate",
                                "param" => $Chanjet_param,
                                "mangerinfo" => $this->mangerinfo
                            ];

                            \App\Jobs\Sale::dispatch($requestData);
                        }
                    }
                }
            }

            DB::commit();

            $message = '操作成功';
            if (!empty($errorMessages)) {
                $message = '部分选项不可操作，系统将会自动跳过，执行处理其余符合审批/开票条件的选项';
            }

            return response()->json([
                'code' => '000',
                'msg' => $message,
                'errors' => $errorMessages
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '批量审核失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 处理单个合同审核
     */
    private function processSingleExamine($id, $examineStatus)
    {
        $one = ModelOutboundordersub::where('id', $id)->first();
        if (!$one) {
            return ['success' => false, 'message' => '子订单不存在'];
        }

        if ($one->examine_status != 2) {
            return ['success' => false, 'message' => '合同已经审核或者未发起审核'];
        }

        //获取订单编号并更新预开票主订单状态
        $order_number = ModelOutboundorder::where('id', $one->p_id)->value('order_number');
        Saleorderinvoice::where('order_number', $order_number)->update(['status' => 2]);

        // 更新审核状态
        ModelOutboundordersub::where('id', $id)->update([
            'examine_status' => $examineStatus,
            'update_at' => time()
        ]);

        return ['success' => true, 'message' => ''];
    }

    /**
     * 未开票总计
     */
    public function invoicedtotal(Request $request)
    {

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $one = ModelOutboundordersub::where([
                ['invoice_status', '<',3],
                ['return_status', '!=', config('constants.return_goods_status.pass')],
                ['cpid', '=',$cpid],
            ])->sum('weight');
        if (!$one) {
            $one = 0;
        }
        return response()->json(['code' => '000', 'msg' => '操作成功','data' => $one]);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 1;
        $utype = $memberinfo['utype']??0;
        $list = ModelOutboundorder::getList($request, $memberinfo, $isgetall);

        $suborderIds = [];
        if (!empty($list['list'])) {
            foreach ($list['list'] as $key => $value) {
                foreach ($value['suborder'] as $k => $v) {
                    $suborderIds[] = $v['id'];
                }
            }
        }

        // 批量查询 subsub 数据
        $subSubOrders = [];
        if (!empty($suborderIds)) {
            $results = ModelOutboundordersubsub::whereIn('p_id', $suborderIds)->get()->toArray();
            foreach ($results as $item) {
                $pid = $item['p_id'];
                $item['total'] = mathfuncmoney('div', $item['total'], 100, 2);
                $subSubOrders[$pid][] = $item;
            }
        }

        // 处理主订单数据
        if ($list['list']) {
            foreach ($list['list'] as $key => $value) {
                foreach ($value['suborder'] as $k => $v) {
                    $list['list'][$key]['suborder'][$k]['weight'] = mathfuncweight('div', $v['weight'], 10000, 4);
                    $list['list'][$key]['suborder'][$k]['unit_price'] = mathfuncmoney('div', $v['unit_price'], 100, 2);
                    $list['list'][$key]['suborder'][$k]['total'] = mathfuncmoney('div', $v['total'], 100, 2);
                    $list['list'][$key]['suborder'][$k]['accrual'] = mathfuncmoney('div', $v['accrual'], 100, 2);
                    $list['list'][$key]['suborder'][$k]['performance'] = mathfuncmoney('div', $v['performance'], 100, 2);

                    // 使用预加载的数据
                    $list['list'][$key]['suborder'][$k]['suborder'] = $subSubOrders[$v['id']] ?? [];
                }
            }
        }



        if ($utype == 3) {
            // 定义表头
            $baseHeader = [
                'order_number' => '销售订单号',
                'document_number' => '单据编号',
                'business_type' => '业务类型',
                'custom_name' => '客户名称',
                'settlement_company' => '结算公司',
                'document_date' => '单据日期',
                'manger_name' => '业务员',
                'bill_type' => '票据类型',
                'wagon_number' => '车船号',
                'driver_phone_number' => '司机电话',
                'remark1' => '备注',

                'warehouse_name1' => '仓库',
                'archive_no1' => '钢材编码',
                'steel_factory_name' => '钢厂',
                'archive_name1' => '品名',
                'archive_spec1' => '规格',
                'archive_material1' => '材质',
                'breed_name' => '品种',
                'pieces1' => '件数',
                'weight1' => '重量（吨）',
                'unit_price1' => '单价（元）',
                'total1' => '金额（元）',
                'invoice_at' => '开票日期',
                'purchase_stockin_order_sn_code' => '进货单号',
                'contract_code' =>  '合同编号',
                'accrual' => '计提',
                'performance' => '业绩',
                'invoice_status' => '开票状态',
                'examine_status' => '审核状态',
                'remark2' => '备注',

                'warehouse_at' => '入库日期',
                'warehouse_name2' => '仓库',
                'archive_name2' => '品名',
                'archive_spec2' => '规格',
                'archive_material2' => '材质',
                'pieces2' => '件数',
                'weight2' => '单件重量',
                'total_weight' => '总重',
                'length' => '长度',
                'stock_num' => '仓位卡号/批号',
                'lock_mem' => '锁定人',
                'lock_date' => '锁定日期',
                'carship_no' => '车/船号',
                'wo_order_sn_code' => '单据号',
                'origin' => '产地',
                'archive_no2' => '钢材编码',
                'layer_num' => '层号',
                'unit_price2' => '单价',
                'total2' => '金额',
                'remark3' => '备注',
            ];

        }else{
            // 定义表头
            $baseHeader = [
                'order_number' => '销售订单号',
                'document_number' => '单据编号',
                'business_type' => '业务类型',
                'custom_name' => '客户名称',
                'settlement_company' => '结算公司',
                'document_date' => '单据日期',
                'manger_name' => '业务员',
                'bill_type' => '票据类型',
                'wagon_number' => '车船号',
                'driver_phone_number' => '司机电话',
                'remark1' => '备注',

                'warehouse_name1' => '仓库',
                'archive_no1' => '钢材编码',
                'steel_factory_name' => '钢厂',
                'archive_name1' => '品名',
                'archive_spec1' => '规格',
                'archive_material1' => '材质',
                'breed_name' => '品种',
                'pieces1' => '件数',
                'weight1' => '重量（吨）',
                'unit_price1' => '单价（元）',
                'total1' => '金额（元）',
                'purchase_stockin_order_sn_code' => '进货单号',
                'accrual' => '计提',
                'performance' => '业绩',
                'invoice_status' => '开票状态',
                'examine_status' => '审核状态',
                'remark2' => '备注',

                'warehouse_at' => '入库日期',
                'warehouse_name2' => '仓库',
                'archive_name2' => '品名',
                'archive_spec2' => '规格',
                'archive_material2' => '材质',
                'pieces2' => '件数',
                'weight2' => '单件重量',
                'total_weight' => '总重',
                'length' => '长度',
                'stock_num' => '仓位卡号/批号',
                'lock_mem' => '锁定人',
                'lock_date' => '锁定日期',
                'carship_no' => '车/船号',
                'wo_order_sn_code' => '单据号',
                'origin' => '产地',
                'archive_no2' => '钢材编码',
                'layer_num' => '层号',
                'unit_price2' => '单价',
                'total2' => '金额',
                'remark3' => '备注',
            ];
        }

        $row = [$baseHeader];

        $invoiceStatusMap = [1 => '未开票', 2 => '开票中', 3 => '已开票'];
        $examineStatusMap = [1 => '未审核', 2 => '审核中', 3 => '已审核'];

        $exceldata = [];
        foreach ($list['list'] as $v1) {
            foreach ($v1['suborder'] as $v2) {
                // 检查第三层是否有数据
                if (empty($v2['suborder'])) {
                    // 如果第三层为空，只添加 $v1 和 $v2 的数据
                    $exceldata[] = [
                        'order_number' => $v1['order_number'],
                        'document_number' => $v1['document_number'],
                        'business_type' => $v1['business_type'] == 1 ? '普通销售' : '',
                        'custom_name' => $v1['custom_name'],
                        'settlement_company' => $v1['settlement_company'],
                        'document_date' => $v1['document_date'] > 0 ? date("Y-m-d H:i:s", $v1['document_date']) : '',
                        'manger_name' => $v1['manger_name'],
                        'bill_type' => $v1['bill_type'] == 1 ? '专用发票' : '',
                        'wagon_number' => $v1['wagon_number'],
                        'driver_phone_number' => $v1['driver_phone_number'] ?? '-',
                        'remark1' => $v1['remark'] ?? '',

                        'warehouse_name1' => $v2['warehouse_name'] ?? '',
                        'archive_no1' => $v2['archive_no'] ?? '',
                        'steel_factory_name' => $v2['steel_factory_name'] ?? '',
                        'archive_name1' => $v2['archive_name'] ?? '',
                        'archive_spec1' => $v2['archive_spec'] ?? '',
                        'archive_material1' => $v2['archive_material'] ?? '',
                        'breed_name' => $v2['breed_name'] ?? '',
                        'pieces1' => $v2['pieces'] ?? '',
                        'weight1' => $v2['weight'] ?? '',
                        'unit_price1' => $v2['unit_price'] ?? '',
                        'total1' => $v2['total'] ?? '',
                        'purchase_stockin_order_sn_code' => $v2['purchase_stockin_order_sn_code'] ?? '',
                        'accrual' => $v2['accrual'] ?? '',
                        'performance' => $v2['performance'] ?? '',
                        'invoice_status' => $invoiceStatusMap[$v2['invoice_status']] ?? '',
                        'examine_status' => $examineStatusMap[$v2['examine_status']] ?? '',
                        'remark2' => $v2['remark'] ?? '',

                        // 第三层数据留空
                        'warehouse_at' => '',
                        'warehouse_name2' => '',
                        'archive_name2' => '',
                        'archive_spec2' => '',
                        'archive_material2' => '',
                        'pieces2' => '',
                        'weight2' => '',
                        'total_weight' => '',
                        'length' => '',
                        'stock_num' => '',
                        'lock_mem' => '',
                        'lock_date' => '',
                        'carship_no' => '',
                        'wo_order_sn_code' => '',
                        'origin' => '',
                        'archive_no2' => '',
                        'layer_num' => '',
                        'unit_price2' => '',
                        'total2' => '',
                        'remark3' => '',

                        // utype == 3 特有字段
                        'invoice_at' => $utype == 3 && $v2['invoice_at'] > 0 ? date("Y-m-d H:i:s", $v2['invoice_at']) : '',
                        'contract_code' => $utype == 3 ? ($v2['contract_code'] ?? '') : '',
                    ];
                } else {
                    // 如果第三层有数据，正常循环
                    foreach ($v2['suborder'] as $v3) {
                        $exceldata[] = [
                            'order_number' => $v1['order_number'],
                            'document_number' => $v1['document_number'],
                            'business_type' => $v1['business_type'] == 1 ? '普通销售' : '',
                            'custom_name' => $v1['custom_name'],
                            'settlement_company' => $v1['settlement_company'],
                            'document_date' => $v1['document_date'] > 0 ? date("Y-m-d H:i:s", $v1['document_date']) : '',
                            'manger_name' => $v1['manger_name'],
                            'bill_type' => $v1['bill_type'] == 1 ? '专用发票' : '',
                            'wagon_number' => $v1['wagon_number'],
                            'driver_phone_number' => $v1['driver_phone_number'] ?? '-',
                            'remark1' => $v1['remark'] ?? '',

                            'warehouse_name1' => $v2['warehouse_name'] ?? '',
                            'archive_no1' => $v2['archive_no'] ?? '',
                            'steel_factory_name' => $v2['steel_factory_name'] ?? '',
                            'archive_name1' => $v2['archive_name'] ?? '',
                            'archive_spec1' => $v2['archive_spec'] ?? '',
                            'archive_material1' => $v2['archive_material'] ?? '',
                            'breed_name' => $v2['breed_name'] ?? '',
                            'pieces1' => $v2['pieces'] ?? '',
                            'weight1' => $v2['weight'] ?? '',
                            'unit_price1' => $v2['unit_price'] ?? '',
                            'total1' => $v2['total'] ?? '',
                            'purchase_stockin_order_sn_code' => $v2['purchase_stockin_order_sn_code'] ?? '',
                            'accrual' => $v2['accrual'] ?? '',
                            'performance' => $v2['performance'] ?? '',
                            'invoice_status' => $invoiceStatusMap[$v2['invoice_status']] ?? '',
                            'examine_status' => $examineStatusMap[$v2['examine_status']] ?? '',
                            'remark2' => $v2['remark'] ?? '',

                            'warehouse_at' => !empty($v3['warehousing_at']) ? date("Y-m-d H:i:s", $v3['warehousing_at']) : '',
                            'warehouse_name2' => $v3['warehouse_name'] ?? '',
                            'archive_name2' => $v3['archive_name'] ?? '',
                            'archive_spec2' => $v3['archive_spec'] ?? '',
                            'archive_material2' => $v3['archive_material'] ?? '',
                            'pieces2' => $v3['pieces'] ?? '',

                            // 这块要和库存对上so 除1000
                            'weight2' => mathfuncweight('div', $v3['weight'] ?? 0, 1000, 4),
                            'total_weight' => mathfuncweight('div', $v3['total_weight'] ?? 0, 1000, 4),
                            'length' => $v3['length'] ?? '',
                            'stock_num' => $v3['stock_num'] ?? '',
                            'lock_mem' => $v3['lock_mem'] ?? '',
                            'lock_date' => $v3['lock_date'] ?? '',
                            'carship_no' => $v3['carship_no'] ?? '',
                            'wo_order_sn_code' => $v3['wo_order_sn_code'] ?? '',
                            'origin' => $v3['origin'] ?? '',
                            'archive_no2' => $v3['archive_no'] ?? '',
                            'layer_num' => $v3['layer_num'] ?? '',
                            'unit_price2' => $v3['unit_price'] ?? '',
                            'total2' => $v3['total'] ?? '',
                            'remark3' => $v3['remark'] ?? '',

                            // utype == 3 特有字段
                            'invoice_at' => $utype == 3 && $v2['invoice_at'] > 0 ? date("Y-m-d H:i:s", $v2['invoice_at']) : '',
                            'contract_code' => $utype == 3 ? ($v2['contract_code'] ?? '') : '',
                        ];
                    }
                }
            }
        }

        $datawith = [];
        $filename = '销售出库单导出.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }

    public function checkWarehouseOut($sales_id = 0){
        $res = ['code' => '001','msg'=>''];
        if($sales_id <= 0){
            $res['msg'] = '销售发货单id,异常';
            return $res;
        }
        $Salesordersub = Salesordersub::where(['p_id' => $sales_id,'is_del' => '1'])->get();
        $is_produced = true;
        foreach ($Salesordersub as $item){
            if($item['produce_status'] == '1'){
                $is_produced = false;
                break;
            }
        }
        $res['code'] = '000';
        $res['is_produced'] = $is_produced;
        return $res;
    }

    /**
     * 批量获取仓库编码，避免N+1查询
     */
    private function getWarehouseCodes($warehouseNames, $cpid)
    {
        $warehouseCodes = WarehouseList::whereIn('warehouse_name', $warehouseNames)
            ->where('cpid', $cpid)
            ->pluck('warehouse_no', 'warehouse_name')
            ->toArray();

        return $warehouseCodes;
    }

    /**
     * 构建销售出库单详情数据
     */
    private function buildSaleDeliveryDetails($suborder, $cpid)
    {
        $SaleDeliveryDetails = [];
        foreach ($suborder as $item) {
            if (($item['weight'] * 100) > 0) {
                $pieces = $item['pieces'] ?? 0;
                $SaleDeliveryDetails[] = [
                    "Warehouse" => ["Code" => WarehouseList::where(['warehouse_name' => $item['warehouse_name'], 'cpid' => $cpid])->value('warehouse_no')],
                    "Inventory" => ["Code" => $item['archive_no']],
                    "Unit" => ["Name" => "吨"],
                    "Unit2" => ["Name" => "件"],
                    "Quantity" => $item['weight'],
                    "Quantity2" => $pieces,
                    "TaxRate" => "0",
                    "OrigTaxPrice" => $item['unit_price'],
                    "OrigTaxAmount" => $item['total'],
                    "OrigDiscount" => $item['total'],
                    "DetailMemo" => $item['remark'],
                    "DynamicPropertyKeys" => ["pubuserdefnvc1", "pubuserdefnvc2", "pubuserdefnvc3", "priuserdefnvc1", "pubuserdefdecm1", "pubuserdefdecm4"],
                    "DynamicPropertyValues" => [
                        $item['steel_factory_name'],
                        $item['breed_name'],
                        $item['archive_material'],
                        strval($pieces),
                        strval($item["accrual"]),
                        strval($item["performance"])
                    ],
                ];
            }
        }
        return $SaleDeliveryDetails;
    }

    /**
     * 构建畅捷参数
     */
    private function buildChanjetParam($outboundinfo, $order_number, $mangerinfo, $SaleDeliveryDetails)
    {
        $param = [
            "dto" => [
                "ExternalCode" => $order_number . '|' . $outboundinfo->document_number,
                "Code" => $outboundinfo->document_number . '|' . $outboundinfo->sales_id,
                "IsModifiedCode" => "true",
                "VoucherDate" => date('Y-m-d', $outboundinfo->document_date),
                "BusinessType" => ["Code" => $outboundinfo->business_type == "1" ? "15" : "16"],
                "InvoiceType" => ["Code" => $outboundinfo->bill_type == "1" ? "01" : "00"],
                "Customer" => ["Code" => Custom::where('id', $outboundinfo->custom_id)->value('company_code')],
                "SaleDeliveryDetails" => $SaleDeliveryDetails
            ]
        ];

        // 车船号
        if ($outboundinfo->wagon_number) {
            $param["dto"]["DynamicPropertyKeys"] = ["pubuserdefnvc1"];
            $param["dto"]["DynamicPropertyValues"] = [$outboundinfo->wagon_number];
        }

        // 结算公司
        if ($outboundinfo->settlement_company) {
            $param["dto"]["SettleCustomer"] = $param["dto"]["Customer"];
        }

        // 部门信息
        if ($mangerinfo['sys_dpm_id']) {
            $param["dto"]["Department"] = ["Code" => $mangerinfo['sys_dpm_id']];
        }

        // 业务员
        if ($mangerinfo['code_no']) {
            $param["dto"]["Clerk"] = ["Code" => $mangerinfo['code_no']];
        }

        // 备注
        if ($outboundinfo->remark) {
            $param["dto"]["Memo"] = $outboundinfo->remark;
        }

        return $param;
    }

}
